package com.devops.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devops.admin.mapper.DOSProjectWebhookMapper;
import com.devops.admin.mapper.DOSWebhookCustomInfoMapper;
import com.devops.admin.model.DOSProjectWebhook;
import com.devops.admin.model.DOSWebhookCustomInfo;
import com.devops.admin.po.DOSWebhookCustomInfoPo;
import com.devops.admin.service.DOSProjectWebhookService;
import com.devops.admin.service.DOSWebhookCustomInfoService;
import com.devops.admin.util.Assert;
import com.devops.admin.util.WebhookUtil;
import com.devops.admin.vo.DOSWebhookCustomInfoVo;
import com.devops.admin.vo.DOSWebhookInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName DOSWebhookCustomInfoServiceImpl
 * Description TODO
 * Author heyabo
 * Date 2022/11/16 10:20
 * Version 1.0
 **/
@Service
public class DOSWebhookCustomInfoServiceImpl extends ServiceImpl<DOSWebhookCustomInfoMapper, DOSWebhookCustomInfo> implements DOSWebhookCustomInfoService {

    @Autowired
    private DOSProjectWebhookMapper dosProjectWebhookMapper;

    @Override
    public DOSWebhookCustomInfoPo getWebhookCustomInfoByWebhookId(Integer id) {
        return baseMapper.getWebhookCustomInfoByWebhookId(id);
    }

    @Override
    public List<DOSWebhookCustomInfoPo> getListByWebhookIds(List<Integer> webhookIds) {
        return baseMapper.getListByWebhookIds(webhookIds);
    }

    @Override
    public boolean saveWebhookCustomInfo(DOSWebhookCustomInfoVo webhookCustomInfoVo) {
        long count = this.count(Wrappers.<DOSWebhookCustomInfo>lambdaQuery()
                .eq(DOSWebhookCustomInfo::getWebhookId,webhookCustomInfoVo.getWebhookId()));
        Assert.isTrue(count == 0,"不可重复添加");
        DOSWebhookCustomInfo webhookCustomInfo = DOSWebhookCustomInfo.builder()
                .clusterIds(webhookCustomInfoVo.getClusterIds())
                .webhookId(webhookCustomInfoVo.getWebhookId())
                .sendType(webhookCustomInfoVo.getSendType())
                .filterType(webhookCustomInfoVo.getFilterType())
                .build();

        if (StrUtil.isNotBlank(webhookCustomInfoVo.getMsgTemplate())) {
            webhookCustomInfo.setMsgTemplate(JSONObject.parseObject(webhookCustomInfoVo.getMsgTemplate()));
        }
        if (StrUtil.isNotEmpty(webhookCustomInfo.getClusterIds()) && webhookCustomInfo.getClusterIds().equals("[]")){
            webhookCustomInfo.setClusterIds(null);
        }
        if (StrUtil.isNotEmpty(webhookCustomInfo.getFilterType()) && webhookCustomInfo.getFilterType().equals("[]")){
            webhookCustomInfo.setFilterType(null);
        }
        // 同步更新webhook的更新时间
        dosProjectWebhookMapper.updateById(DOSProjectWebhook.builder().id(webhookCustomInfoVo.getWebhookId()).build());
        return this.save(webhookCustomInfo);
    }

    @Override
    public boolean updateWebhookCustomInfo(DOSWebhookCustomInfoVo webhookCustomInfoVo) {
        DOSWebhookCustomInfo webhookCustomInfo = DOSWebhookCustomInfo.builder()
                .clusterIds(webhookCustomInfoVo.getClusterIds())
                .id(webhookCustomInfoVo.getId())
                .sendType(webhookCustomInfoVo.getSendType())
                .filterType(webhookCustomInfoVo.getFilterType())
                .build();
        if (StrUtil.isNotBlank(webhookCustomInfoVo.getMsgTemplate())) {
            JSONObject jsonObject = JSONObject.parseObject(webhookCustomInfoVo.getMsgTemplate());
            webhookCustomInfo.setMsgTemplate(jsonObject);
        }
        if (StrUtil.isNotEmpty(webhookCustomInfo.getClusterIds()) && webhookCustomInfo.getClusterIds().equals("[]")){
            webhookCustomInfo.setClusterIds(null);
        }
        if (StrUtil.isNotEmpty(webhookCustomInfo.getFilterType()) && webhookCustomInfo.getFilterType().equals("[]")){
            webhookCustomInfo.setFilterType(null);
        }
        // 同步更新webhook的更新时间
        dosProjectWebhookMapper.updateById(DOSProjectWebhook.builder().id(webhookCustomInfoVo.getWebhookId()).build());
        return this.updateById(webhookCustomInfo);
    }

    @Override
    public String testWebhookCustomInfo(DOSWebhookInfoVo webhookInfoVo) {
        String url;
        try {
            url = WebhookUtil.dealWebHook(webhookInfoVo.getWebhook(),webhookInfoVo.getSecret());
        } catch (Exception e) {
            e.printStackTrace();
            return "webhook连接异常";
        }

        String msgTemplate = webhookInfoVo.getMsgTemplate();
        if (StrUtil.isEmpty(msgTemplate)){
            msgTemplate = getDefaultTemplate();
        }

        JSONObject msgJson = JSONObject.parseObject(msgTemplate);

        HttpResponse response = HttpRequest.post(url).body(msgJson.toJSONString()
                , "application/json;charset=UTF-8").execute();
        if (response != null) {
            if (response.getStatus() == 200) {
                return "webhook连接正常";
            }
        }
        return "webhook连接异常";
    }

    private String getDefaultTemplate() {
        String singleLineStr = "##### #{msg}\n" + "> - #{startTime} \n" + "> - #{Message}\n" + "> - #{endTime}";
        cn.hutool.json.JSONObject msgJson = new cn.hutool.json.JSONObject();
        //md格式
        cn.hutool.json.JSONObject mdJson = new cn.hutool.json.JSONObject();
        mdJson.set("title", "#{title}");
        mdJson.set("text",singleLineStr);
        msgJson.set("msgtype","markdown");
        msgJson.set("markdown",mdJson);
        return msgJson.toString();
    }
}
